package sql_models

import (
	"encoding/json"
	"fmt"

	"gorm.io/gorm"
)

type Shop struct {
	ID      string   `gorm:"primaryKey"`           // 采用 string 类型的 ID
	Name    string   `gorm:"size:100;not null"`    // 店铺名称
	Address string   `gorm:"size:255"`             // 地址
	Rooms   []Room   `gorm:"foreignKey:ShopID"`    // 关联房间
	IDCards []IDCard `gorm:"foreignKey:ShopID"`    // 关联ID卡号
}

type Room struct {
	ID     uint   `gorm:"primaryKey"`           // 房间ID，主键
	RoomID string `gorm:"size:50;not null"`     // 房间编号，作为关联设备的ID
	ShopID string `gorm:"size:100"`             // 关联的店铺ID
}

type IDCard struct {
	ID         uint   `gorm:"primaryKey"`
	CardNumber string `gorm:"size:100;not null"`    // ID卡号
	ShopID     string `gorm:"size:100"`             // 关联的店铺ID
}

// 定义房间简化结构
type SimplifiedRoom struct {
    RoomName string `json:"RoomName"`
}

// 定义返回结构
type ShopMsg struct {
    ShopMsg struct {
        ID       string   `json:"ID"`
        Address  string   `json:"addr"`
        RoomList []string `json:"roomlist"` // roomlist 现在是字符串数组
    } `json:"shop-msg"`
}

func GetRoomsByShopID(shopID string) (string, error) {
    var rooms []Room
    var shop Shop

    // 查询数据库中的房间列表
    if err := DB.Where("shop_id = ?", shopID).Find(&rooms).Error; err != nil {
        return "", err
    }

    // 查询Shop的地址等信息
    if err := DB.First(&shop, "id = ?", shopID).Error; err != nil {
        return "", err
    }

    // 构建房间号的字符串数组
    roomNumbers := make([]string, len(rooms))
    for i, room := range rooms {
        roomNumbers[i] = room.RoomID
    }

    // 组装返回结构
    result := ShopMsg{}
    result.ShopMsg.ID = shop.ID
    result.ShopMsg.Address = shop.Address
    result.ShopMsg.RoomList = roomNumbers

    // 转换为JSON
    response, err := json.Marshal(result)
    if err != nil {
        return "", err
    }
    return string(response), nil
}

func MatchRoomByShopIDAndRoomNumber(shopID string, roomNumber string) (bool, error) {
	var room Room
	// 查询数据库中是否存在匹配的房间号
	if err := DB.Where("shop_id = ? AND room_id = ?", shopID, roomNumber).First(&room).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func MatchIDCardByShopIDAndCardNumber(shopID string, cardNumber string) (bool, error) {
	var idCard IDCard
	// 查询数据库中是否存在匹配的 ID 卡号
	if err := DB.Where("shop_id = ? AND card_number = ?", shopID, cardNumber).First(&idCard).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func shop_test() {
	// 创建两个Shop，每个Shop有多个Room和IDCard
	shop1 := Shop{
		ID:      "60001",
		Name:    "Shop One",
		Address: "123 First Street",
		Rooms: []Room{
			{RoomID: "101"},
			{RoomID: "102"},
			{RoomID: "103"},
		},
		IDCards: []IDCard{
			{CardNumber: "ID-123456"},
			{CardNumber: "ID-654321"},
		},
	}

	shop2 := Shop{
		ID:      "60002",
		Name:    "Shop Two",
		Address: "456 Second Street",
		Rooms: []Room{
			{RoomID: "102"}, // 共享Room 102
			{RoomID: "104"},
			{RoomID: "105"},
		},
		IDCards: []IDCard{
			{CardNumber: "ID-789012"},
			{CardNumber: "ID-210987"},
		},
	}

	// 检查Shop ID是否已经存在，避免重复创建
	var existingShop Shop
	if err := DB.First(&existingShop, "id = ?", shop1.ID).Error; err == gorm.ErrRecordNotFound {
		DB.Create(&shop1)
		fmt.Println("Shop 1 created")
	} else {
		fmt.Println("Shop 1 already exists")
	}

	// 重置 existingShop 变量，确保查询正确进行
	existingShop = Shop{} 
	if err := DB.First(&existingShop, "id = ?", shop2.ID).Error; err == gorm.ErrRecordNotFound {
		DB.Create(&shop2)
		fmt.Println("Shop 2 created")
	} else {
		fmt.Println("Shop 2 already exists")
	}

	// 测试获取房间列表
	fmt.Println("Getting rooms for Shop 60001:")
	roomsJSON, err := GetRoomsByShopID("60001")
	if err != nil {
		fmt.Println("Error getting rooms:", err)
	} else {
		fmt.Println("Shop with rooms:", roomsJSON)
	}

	// 测试匹配房间号
	fmt.Println("Matching Room '101' in Shop 60001:")
	matched, err := MatchRoomByShopIDAndRoomNumber("60001", "101")
	if err != nil {
		fmt.Println("Error matching room:", err)
	} else {
		fmt.Printf("Room '101' match result: %v\n", matched)
	}

	fmt.Println("Matching Room '201' in Shop 60001:")
	matched, err = MatchRoomByShopIDAndRoomNumber("60001", "201")
	if err != nil {
		fmt.Println("Error matching room:", err)
	} else {
		fmt.Printf("Room '201' match result: %v\n", matched)
	}

	// 测试匹配ID卡号
	fmt.Println("Matching IDCard 'ID-123456' in Shop 60001:")
	matched, err = MatchIDCardByShopIDAndCardNumber("60001", "ID-123456")
	if err != nil {
		fmt.Println("Error matching IDCard:", err)
	} else {
		fmt.Printf("IDCard 'ID-123456' match result: %v\n", matched)
	}

	fmt.Println("Matching IDCard 'ID-999999' in Shop 60001:")
	matched, err = MatchIDCardByShopIDAndCardNumber("60001", "ID-999999")
	if err != nil {
		fmt.Println("Error matching IDCard:", err)
	} else {
		fmt.Printf("IDCard 'ID-999999' match result: %v\n", matched)
	}
}
